require('es6-promise').polyfill();

import axios from 'axios'

export const LOAD_MENUS = 'LOAD_MENUS';

export function createMenu() {
  return {
    type: 'CREATE_MENU'
  }
}
export function editMenu(data) {
  return {
    type: 'EDIT_MENU',
    data,
    date: Date.now()
  };
}
export function deleteMenu(id) {
  return {
    type: 'DELETE_MENU',
    id
  };
}

function loadMenus(data) {
  return {
    type: 'LOAD_MENUS',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_MENUS',
    error
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}


export function loadMenusAsync() {
  return function(dispatch) {
    return axios.post('/api/menus').then(
      resp => dispatch(loadMenus(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function createMenuAsync(data) {
  return function(dispatch) {
    return axios.post('/api/menus/create', data)
    .then(resp => dispatch(apiMsgAction("保存成功!")),
          error => dispatch(apiMsgAction(error.data.errMsg))
        )
  }
}

export function resetMenuAsync() {
  return function(dispatch) {
    return axios.post('/api/menus/reset')
    .then((resp) => {
      dispatch(loadMenusAsync())
      alert("初始化成功!")
    })
    .catch((error) =>{
      dispatch(apiMsgAction(error.data.errMsg))
    })
  }
}
